<template>
  <div class="settings-container">
    <a-card :bordered="false">
      <a-tabs v-model="activeTabKey">
        <a-tab-pane key="basic" tab="基本信息">
          <div class="basic-info-layout">
            <!-- 左侧信息展示 -->
            <div class="left-panel">
              <div class="user-profile">
                <div class="avatar-display">
                  <AvatarImage 
                    :src="basicInfoForm.avatar" 
                    :size="120" 
                  />
                </div>
                <div class="user-info">
                  <h2 class="username">{{ basicInfoForm.realName || basicInfoForm.username }}</h2>
                  <p class="user-dept">{{ userDeptName }}</p>
                  <p class="user-role">{{ userRoleName }}</p>
                  <p class="join-time">加入时间：{{ userJoinTime }}</p>
                </div>
                <div class="user-stats">
                  <a-row>
                    <a-col :span="8">
                      <div class="stat-item">
                        <p class="stat-value">{{ userStats.tasks || 0 }}</p>
                        <p class="stat-label">待办任务</p>
                      </div>
                    </a-col>
                    <a-col :span="8">
                      <div class="stat-item">
                        <p class="stat-value">{{ userStats.projects || 0 }}</p>
                        <p class="stat-label">参与项目</p>
                      </div>
                    </a-col>
                    <a-col :span="8">
                      <div class="stat-item">
                        <p class="stat-value">{{ userStats.teams || 0 }}</p>
                        <p class="stat-label">团队</p>
                      </div>
                    </a-col>
                  </a-row>
                </div>
              </div>
            </div>
            
            <!-- 右侧可编辑信息 -->
            <div class="right-panel">
              <a-form
                :model="basicInfoForm"
                :rules="basicInfoRules"
                :label-col="{ span: 4 }"
                :wrapper-col="{ span: 18 }"
                ref="basicInfoFormRef"
              >
                <a-form-item label="头像" name="avatar">
                  <div class="avatar-wrapper">
                    <AvatarUpload v-model:value="basicInfoForm.avatar" />
                  </div>
                </a-form-item>
                <a-form-item label="用户名" name="username">
                  <a-input v-model:value="basicInfoForm.username" placeholder="请输入用户名" disabled />
                </a-form-item>
                <a-form-item label="真实姓名" name="realName">
                  <a-input v-model:value="basicInfoForm.realName" placeholder="请输入真实姓名" />
                </a-form-item>
                <a-form-item label="手机号码" name="phoneNumber">
                  <a-input v-model:value="basicInfoForm.phoneNumber" placeholder="请输入手机号码" />
                </a-form-item>
                <a-form-item label="邮箱" name="email">
                  <a-input v-model:value="basicInfoForm.email" placeholder="请输入邮箱" />
                </a-form-item>
                <a-form-item label="所在地区">
                  <div style="display: flex; gap: 8px;">
                    <a-form-item name="province" style="margin-bottom: 0;">
                      <a-input 
                        v-model:value="basicInfoForm.province" 
                        placeholder="省份" 
                        style="width: 100px;" 
                        readonly
                      />
                    </a-form-item>
                    <a-form-item name="city" style="margin-bottom: 0;">
                      <a-input 
                        v-model:value="basicInfoForm.city" 
                        placeholder="城市" 
                        style="width: 100px;" 
                        readonly
                      />
                    </a-form-item>
                    <a-form-item name="district" style="margin-bottom: 0;">
                      <a-input 
                        v-model:value="basicInfoForm.district" 
                        placeholder="区县" 
                        style="width: 100px;" 
                        readonly
                      />
                    </a-form-item>
                    <a-button type="dashed" @click="showMapModal">
                      <template #icon><environment-outlined /></template>
                      地图选择
                    </a-button>
                  </div>
                </a-form-item>
                <a-form-item label="详细地址" name="address">
                  <a-textarea
                    v-model:value="basicInfoForm.address"
                    placeholder="请输入详细地址（如：小区名称、楼栋号、单元室等）"
                    :rows="3"
                    :maxlength="200"
                    show-count
                  />
                </a-form-item>
                <a-form-item label="自我介绍" name="introduction">
                  <a-textarea 
                    v-model:value="basicInfoForm.introduction" 
                    placeholder="请输入自我介绍" 
                    :rows="4" 
                    :maxlength="200" 
                    show-count 
                  />
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 18, offset: 4 }">
                  <a-button type="primary" @click="saveBasicInfo" :loading="basicInfoLoading">保存</a-button>
                </a-form-item>
              </a-form>
            </div>
          </div>
        </a-tab-pane>

        <a-tab-pane key="password" tab="修改密码">
          <a-form
            :model="passwordForm"
            :rules="passwordRules"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 18 }"
            ref="passwordFormRef"
          >
            <a-form-item label="当前密码" name="oldPassword">
              <a-input-password v-model:value="passwordForm.oldPassword" placeholder="请输入当前密码" />
            </a-form-item>
            <a-form-item label="新密码" name="newPassword">
              <a-input-password v-model:value="passwordForm.newPassword" placeholder="请输入新密码" />
            </a-form-item>
            <a-form-item label="确认新密码" name="confirmPassword">
              <a-input-password v-model:value="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 18, offset: 4 }">
              <a-button type="primary" @click="changePassword" :loading="passwordLoading">修改密码</a-button>
            </a-form-item>
          </a-form>
        </a-tab-pane>

        <a-tab-pane key="signature" tab="电子签名">
          <div class="signature-container">
            <a-tabs v-model="signatureTabKey">
              <a-tab-pane key="upload" tab="上传签名">
                <a-form
                  :model="signatureUploadForm"
                  :label-col="{ span: 4 }"
                  :wrapper-col="{ span: 18 }"
                >
                  <a-form-item label="签名图片" name="signatureImage">
                    <a-upload
                      list-type="picture-card"
                      :file-list="signatureFileList"
                      :custom-request="uploadSignature"
                      :before-upload="beforeSignatureUpload"
                      @change="handleSignatureChange"
                      @remove="handleSignatureRemove"
                      @preview="handleSignaturePreview"
                    >
                      <div v-if="signatureFileList.length < 1">
                        <plus-outlined />
                        <div style="margin-top: 8px">上传</div>
                      </div>
                    </a-upload>
                    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handlePreviewCancel">
                      <img alt="example" style="width: 100%" :src="previewImage" />
                    </a-modal>
                  </a-form-item>
                  <a-form-item :wrapper-col="{ span: 18, offset: 4 }">
                    <a-button type="primary" @click="saveSignatureImage" :loading="signatureUploadLoading">保存签名</a-button>
                  </a-form-item>
                </a-form>
              </a-tab-pane>
              
              <a-tab-pane key="draw" tab="在线签名">
                <div class="signature-pad-container">
                  <div class="signature-controls" style="margin-bottom: 16px;">
                    <a-row>
                      <a-col :span="12">
                        <a-space>
                          <a-tooltip title="画笔颜色">
                            <a-popover title="选择画笔颜色" trigger="click" placement="bottom">
                              <template #content>
                                <div class="color-picker">
                                  <div 
                                    v-for="color in penColors" 
                                    :key="color" 
                                    class="color-item" 
                                    :style="{ backgroundColor: color }" 
                                    @click="changePenColor(color)"
                                  ></div>
                                </div>
                                <div style="margin-top: 8px;">
                                  <input 
                                    type="color" 
                                    v-model="signOptions.penColor" 
                                    style="width: 100%;" 
                                    @change="changePenColor(signOptions.penColor)"
                                  />
                                </div>
                              </template>
                              <a-button>
                                <div class="color-preview" :style="{ backgroundColor: signOptions.penColor }"></div>
                                画笔颜色
                              </a-button>
                            </a-popover>
                          </a-tooltip>
                          
                          <a-tooltip title="画笔粗细">
                            <a-input-number 
                              v-model="signOptions.minWidth" 
                              :min="0.5" 
                              :max="5" 
                              :step="0.5"
                              style="width: 100px"
                            />
                          </a-tooltip>
                        </a-space>
                      </a-col>
                      <a-col :span="12" style="text-align: right">
                        <a-space>
                          <a-button @click="undoSignature">
                            <template #icon><undo-outlined /></template>
                            撤销
                          </a-button>
                          <a-button @click="clearSignature">
                            <template #icon><delete-outlined /></template>
                            清空
                          </a-button>
                          <a-button type="primary" @click="saveHandwrittenSignature" :loading="handwrittenSignatureLoading">
                            保存签名
                          </a-button>
                        </a-space>
                      </a-col>
                    </a-row>
                  </div>
                  <div class="signature-pad-wrapper">
                    <VueSignaturePad ref="signaturePadRef" :options="signOptions" style="background-color: #fff" />
                  </div>
                </div>
              </a-tab-pane>
            </a-tabs>
            
            <div class="signature-preview" v-if="userSignature">
              <a-divider>当前使用的签名</a-divider>
              <div class="current-signature">
                <img :src="userSignature" alt="当前签名" class="signature-image" />
                <div class="signature-actions">
                  <a-space>
                    <a-button type="primary" danger @click="removeSignature" :loading="removeSignatureLoading">删除签名</a-button>
                    <a-button @click="downloadSignature">下载签名</a-button>
                  </a-space>
                </div>
              </div>
            </div>
          </div>
        </a-tab-pane>
        
        <a-tab-pane key="security" tab="安全设置">
          <a-list item-layout="horizontal" :data-source="securitySettings">
            <template #renderItem="{ item }">
              <a-list-item>
                <a-list-item-meta>
                  <template #title>{{ item.title }}</template>
                  <template #description>{{ item.description }}</template>
                </a-list-item-meta>
                <template #extra>
                  <a-button type="link" @click="handleSecurityAction(item.key)">{{ item.action }}</a-button>
                </template>
              </a-list-item>
            </template>
          </a-list>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    
    <!-- 地图选择弹窗 -->
    <a-modal
      :open="mapModalVisible"
      title="选择地址位置"
      width="80%"
      style="max-width: 1000px;"
      @ok="confirmMapSelection"
      @cancel="cancelMapSelection"
    >
      <div class="map-modal-content">
        <MapPicker
          ref="mapPickerRef"
          v-model="mapLocation"
          @select="handleMapAddress"
          @confirm="handleMapConfirm"
        />
      </div>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch, computed } from 'vue';
import { message } from 'ant-design-vue';
import { PlusOutlined, UndoOutlined, DeleteOutlined, EnvironmentOutlined, SearchOutlined } from '@ant-design/icons-vue';
import AvatarUpload from '@/views/system/user/AvatarUpload.vue';
import AvatarImage from '@/components/AvatarImage.vue';
import MapPicker from '@/components/MapPicker.vue';
import { VueSignaturePad } from 'vue-signature-pad';
import Api from '@/api';
import type { UploadFile, UploadProps } from 'ant-design-vue';
import type { Rule as FormRule } from 'ant-design-vue/es/form';
import helper from '@/utils/helper';


// 生命周期钩子
onMounted(async () => {
  await getUserInfo();
});

// 声明全局类型
declare global {
  interface Window {
    AMap: any;
  }
}

type FileType = Parameters<NonNullable<UploadProps['beforeUpload']>>[0];

// 标签页活动Key
const activeTabKey = ref('basic');
const signatureTabKey = ref('upload');
// 移除addressTabKey，改为地图弹窗控制
const mapModalVisible = ref(false);
const selectedMapAddress = ref<any>(null);

// 基本信息表单
const basicInfoFormRef = ref();
const basicInfoLoading = ref(false);
const basicInfoForm = reactive({
    id:'',
  username: '',
  realName: '',
  phoneNumber: '',
  email: '',
  avatar: '',
  introduction: '',
  signature:'',
  // 地址相关字段
  province: '', // 省份名称
  city: '', // 城市名称
  district: '', // 区县名称
  address: '', // 详细地址
  addressLng: 0, // 经度
  addressLat: 0, // 纬度
});
const signaturePadRef = ref();
const penColors = ['#000000', '#1890ff', '#f5222d', '#52c41a', '#722ed1', '#fa8c16'];
const signOptions=reactive({
		penColor: '#000000',
		minWidth: 1.0,
}) 
const basicInfoRules = {
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }] as FormRule[],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ] as FormRule[],
  phoneNumber: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ] as FormRule[]
};
 const getAvatarUrl = (item: any) => {
  if (!item)
    return "icon/male.png";
  return /^https?:\/\//.test(item) ? item : Api.file.download2(item) ;
};
// 密码表单
const passwordFormRef = ref();
const passwordLoading = ref(false);
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
});

const passwordRules = {
  oldPassword: [{ required: true, message: '请输入当前密码', trigger: 'blur' }] as FormRule[],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ] as FormRule[],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string) => {
        if (value !== passwordForm.newPassword) {
          return Promise.reject('两次输入的密码不一致');
        }
        return Promise.resolve();
      },
      trigger: 'blur'
    }
  ] as FormRule[]
};

// 签名上传
const signatureUploadLoading = ref(false);
const handwrittenSignatureLoading = ref(false);
const removeSignatureLoading = ref(false);
const signatureUploadForm = reactive({
  signatureImage: '',
});

const signatureFileList = ref<UploadFile[]>([]);
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');


// 当前签名
const userSignature = ref('');

// 安全设置
const securitySettings = [
  {
    key: 'mfa',
    title: '两步验证',
    description: '启用两步验证后，登录时将需要额外的验证码',
    action: '未启用'
  },
  {
    key: 'loginLog',
    title: '登录日志',
    description: '查看您的账号登录记录',
    action: '查看'
  },
  {
    key: 'devices',
    title: '已登录设备',
    description: '管理您当前登录的所有设备',
    action: '管理'
  }
];

// 添加用户部门、角色和加入时间等信息
const userDeptName = ref('');
const userRoleName = ref('');
const userJoinTime = ref('');
const userStats = reactive({
  tasks: 12,
  projects: 5,
  teams: 3
});

// 地图定位相关
const mapPickerRef = ref<any>(null);

// 地图定位数据
const mapLocation = computed({
  get: () => ({
    address: basicInfoForm.address,
    location: { lng: basicInfoForm.addressLng, lat: basicInfoForm.addressLat }
  }),
  set: (value: any) => {
    if (value) {
      selectedMapAddress.value = parseAddressInfo(value.address, value.location);
    }
  }
});

// 地址解析函数 - 将完整地址分解为省市区和详细地址
const parseAddressInfo = (fullAddress: string, location: any) => {
  // 常见的省市区关键词
  const provinceRegex = /(.*?省|.*?自治区|.*?市|.*?特别行政区)/;
  const cityRegex = /(.*?市|.*?州|.*?盟|.*?地区)/;
  const districtRegex = /(.*?区|.*?县|.*?市|.*?旗)/;
  
  let province = '';
  let city = '';
  let district = '';
  let detailAddress = fullAddress;
  
  // 解析省份
  const provinceMatch = fullAddress.match(provinceRegex);
  if (provinceMatch) {
    province = provinceMatch[1];
    detailAddress = detailAddress.replace(province, '');
  }
  
  // 解析城市
  const cityMatch = detailAddress.match(cityRegex);
  if (cityMatch) {
    city = cityMatch[1];
    detailAddress = detailAddress.replace(city, '');
  }
  
  // 解析区县
  const districtMatch = detailAddress.match(districtRegex);
  if (districtMatch) {
    district = districtMatch[1];
    detailAddress = detailAddress.replace(district, '');
  }
  
  return {
    fullAddress: fullAddress,
    areaText: `${province}${city}${district}`.replace(/^\s+|\s+$/g, ''),
    detailAddress: detailAddress.replace(/^\s+|\s+$/g, ''),
    province: province,
    city: city,
    district: district,
    location: location
  };
};



// 显示地图选择弹窗
const showMapModal = () => {
  mapModalVisible.value = true;
  selectedMapAddress.value = null;
};

// 确认地图选择
const confirmMapSelection = () => {
  
  if (selectedMapAddress.value) {
    // 填入省市区信息
    basicInfoForm.province = selectedMapAddress.value.province || '';
    basicInfoForm.city = selectedMapAddress.value.city || '';
    basicInfoForm.district = selectedMapAddress.value.district || '';
    
    // 填入详细地址
    basicInfoForm.address = selectedMapAddress.value.detailAddress;
    
    // 更新位置信息
    basicInfoForm.addressLng = selectedMapAddress.value.location.lng;
    basicInfoForm.addressLat = selectedMapAddress.value.location.lat;
    
    message.success('地址信息已更新');
  }
  
  mapModalVisible.value = false;
};

// 取消地图选择
const cancelMapSelection = () => {
  mapModalVisible.value = false;
  selectedMapAddress.value = null;
};

// 修改handleMapAddress方法
const handleMapAddress = (value: any) => {
  if (value) {
    selectedMapAddress.value = parseAddressInfo(value.address, value.location);
  }
};

// 处理地图确认事件
const handleMapConfirm = (value: any) => {
  if (value) {
    const addressInfo = parseAddressInfo(value.address, value.location);
    
    // 填入省市区信息
    basicInfoForm.province = addressInfo.province || '';
    basicInfoForm.city = addressInfo.city || '';
    basicInfoForm.district = addressInfo.district || '';
    
    // 填入详细地址
    basicInfoForm.address = addressInfo.detailAddress;
    
    // 更新位置信息
    basicInfoForm.addressLng = value.location.lng;
    basicInfoForm.addressLat = value.location.lat;
    
    // 关闭弹框
    mapModalVisible.value = false;
    
    //message.success('地址已选择并填入表单');
  }
};

// 生命周期钩子
onMounted(async () => {
  await getUserInfo();

  
});

// 获取用户信息
const getUserInfo = async () => {
  try {
    const userInfo = await Api.user.current();
    if (userInfo) {
        basicInfoForm.id=userInfo.id || '';
      basicInfoForm.username = userInfo.userName || '';
      basicInfoForm.realName = userInfo.realName || '';
      basicInfoForm.phoneNumber = userInfo.mobile || '';
      basicInfoForm.email = userInfo.email||''; // 自定义字段，API中可能不存在
      basicInfoForm.avatar = userInfo.avatar || '';
      basicInfoForm.introduction = userInfo.introduction||''; // 自定义字段，API中可能不存在
      basicInfoForm.signature=userInfo.signature;
      // 设置地址信息
      basicInfoForm.province = userInfo.province || '';
      basicInfoForm.city = userInfo.city || '';
      basicInfoForm.district = userInfo.district || '';
      basicInfoForm.address = userInfo.address || '';
      basicInfoForm.addressLng = userInfo.addressLng || 0;
      basicInfoForm.addressLat = userInfo.addressLat || 0;
      userDeptName.value=userInfo.deptName;
      if (userInfo.creatTime) {
        const date = new Date(userInfo.creatTime);
        userJoinTime.value = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
      } else {
        userJoinTime.value = '';
      }
      getUserSignature()
    }
  } catch (error) {
    message.error('获取用户信息失败');
  }
};

// 获取用户签名
const getUserSignature = async () => {
  try {
  
    if (basicInfoForm.signature ) {
      // 设置签名URL
      userSignature.value = helper.toApiUrl(`file/download2?md5=${basicInfoForm.signature}`);
    }
  } catch (error) {
    console.error('获取用户签名失败', error);
  }
};

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    var res = await basicInfoFormRef.value.validate();
    basicInfoLoading.value = true;
    // 只取基础信息字段
    const payload = {
      id: basicInfoForm.id,
      avatar: basicInfoForm.avatar,
      realName: basicInfoForm.realName,
      mobile: basicInfoForm.phoneNumber,
      email: basicInfoForm.email,
      province: basicInfoForm.province,
      city: basicInfoForm.city,
      district: basicInfoForm.district,
      address: basicInfoForm.address,
      introduction: basicInfoForm.introduction,
      // 经纬度和location
      addressLng: basicInfoForm.addressLng,
      addressLat: basicInfoForm.addressLat,
    };
    var u = await Api.user.saveBasicInfo(payload);
    if (u) {
      message.success("保存成功");
    }
  } catch (error) {
    console.error('保存失败', error);
  } finally {
    basicInfoLoading.value = false;
  }
};





// 修改密码
const changePassword = async () => {
  try {
    await passwordFormRef.value.validate();
    passwordLoading.value = true;
    
    // 调用API修改密码
    await Api.account.accountPassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword,
    });
    
    message.success('密码修改成功，请重新登录');
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';
    
    // 可选：退出登录
    // store.dispatch('user/logout');
  } catch (error) {
    console.error('修改密码失败', error);
  } finally {
    passwordLoading.value = false;
  }
};

// 签名上传相关
const beforeSignatureUpload = (file: FileType) => {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    message.error('只能上传图片文件!');
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error('图片必须小于2MB!');
  }
  return isImage && isLt2M;
};

const uploadSignature = async (options: any) => {
  try {
    // 调用API上传签名
    // const { filename } = await Api.toolsUpload.uploadUpload({ file: options.file });
    // signatureUploadForm.signatureImage = filename;
    options.onSuccess();
  } catch (error) {
    options.onError();
    console.error('上传签名失败', error);
  }
};

const handleSignatureChange = ({ file }: any) => {
  file.status = 'done';
  signatureFileList.value = [file];
};

const handleSignatureRemove = () => {
  signatureUploadForm.signatureImage = '';
  signatureFileList.value = [];
};

const handleSignaturePreview = async (file: UploadFile) => {
  previewImage.value = file.url || (file.preview as string);
  previewVisible.value = true;
  previewTitle.value = file.name || '';
};

const handlePreviewCancel = () => {
  previewVisible.value = false;
};

const saveSignatureImage = async () => {
  try {
    if (signatureFileList.value.length === 0) {
      return message.warning('请先上传签名图片');
    }
    
    signatureUploadLoading.value = true;
    
    // 获取文件对象
    const fileObj = signatureFileList.value[0].originFileObj;
    if (!fileObj) {
      throw new Error('文件对象不存在');
    }
    
    // 使用uploadAvatar上传签名图片
    const uploadResult = await Api.file.uploadAvatar(fileObj);
    
    if (uploadResult && uploadResult.md5) {
      // 调用savesignature保存MD5到用户Signature字段
      await Api.user.savesignature({
        signatureMd5: uploadResult.md5
      });
      
      message.success('签名保存成功');
      userSignature.value = uploadResult.url;
    } else {
      throw new Error('签名上传失败');
    }
  } catch (error) {
    console.error('保存签名失败', error);
    message.error('保存签名失败：' + (error.message || '未知错误'));
  } finally {
    signatureUploadLoading.value = false;
  }
};



// 删除签名
const removeSignature = async () => {
  try {
    removeSignatureLoading.value = true;
    
    // 调用API删除签名
     await Api.user.removeSignature();
    
    message.success('签名已删除');
    userSignature.value = '';
  } catch (error) {
    console.error('删除签名失败', error);
  } finally {
    removeSignatureLoading.value = false;
  }
};

// 下载签名
const downloadSignature = () => {
  if (!userSignature.value) return;
  
  const link = document.createElement('a');
  link.href = userSignature.value;
  link.download = '我的签名.png';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 安全设置相关
const handleSecurityAction = (key: string) => {
  switch (key) {
    case 'mfa':
      // 跳转到两步验证设置页面
      break;
    case 'loginLog':
      // 跳转到登录日志页面
      break;
    case 'devices':
      // 跳转到设备管理页面
      break;
  }
};

// 签名绘制相关
const changePenColor = (color: string) => {
  signOptions.penColor = color;
  if (signaturePadRef.value) {
    signaturePadRef.value.changeOption({ penColor: color });
    signaturePadRef.value.refresh();
  }
};

const undoSignature = () => {
  if (signaturePadRef.value) {
    signaturePadRef.value.undoSignature();
  }
};

const clearSignature = () => {
  if (signaturePadRef.value) {
    signaturePadRef.value.clearSignature();
  }
};
// 监视画笔粗细变化
watch(signOptions, () => {
	signaturePadRef.value.signaturePad.penColor = signOptions.penColor;
	signaturePadRef.value.signaturePad.minWidth = signOptions.minWidth;
});

const saveHandwrittenSignature = async () => {
  try {
    if (!signaturePadRef.value) return;
    
    const { isEmpty } = signaturePadRef.value.saveSignature();
    if (isEmpty) {
      return message.warning('请先绘制签名');
    }
    
    handwrittenSignatureLoading.value = true;
    
    // 获取签名图片数据
    const { data } = signaturePadRef.value.saveSignature();
    
    // 将Base64图片转换为Blob，再转为File对象
    const base64Data = data.split(',')[1];
    const byteCharacters = atob(base64Data);
    const byteArrays = [] as number[];
    
    for (let i = 0; i < byteCharacters.length; i++) {
      byteArrays.push(byteCharacters.charCodeAt(i));
    }
    
    const blob = new Blob([new Uint8Array(byteArrays)], { type: 'image/png' });
    const fileName = `signature_${new Date().getTime()}.png`;
    const file = new File([blob], fileName, { type: 'image/png' });
    
    // 使用uploadAvatar上传签名图片
    const uploadResult = await Api.file.uploadAvatar(file);
    
    if (uploadResult && uploadResult.md5) {
      // 调用savesignature保存MD5到用户Signature字段
      await Api.user.savesignature({
        signatureMd5: uploadResult.md5
      });
      
      message.success('签名保存成功');
      userSignature.value = uploadResult.url;
    } else {
      throw new Error('签名上传失败');
    }
  } catch (error) {
    console.error('保存签名失败', error);
    message.error('保存签名失败：' + (error.message || '未知错误'));
  } finally {
    handwrittenSignatureLoading.value = false;
  }
};
</script>

<style lang="less" scoped>
.settings-container {
  padding: 16px;
  
  .basic-info-layout {
    display: flex;
    gap: 24px;
    
    @media (max-width: 768px) {
      flex-direction: column;
    }
    
    .left-panel {
      width: 280px;
      flex-shrink: 0;
      
      @media (max-width: 768px) {
        width: 100%;
        margin-bottom: 24px;
      }
      
      .user-profile {
        background-color: #fff;
        border-radius: 4px;
        padding: 24px;
        box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
        text-align: center;
        
        .avatar-display {
          margin-bottom: 16px;
          display: flex;
          justify-content: center;
        }
        
        .user-info {
          margin-bottom: 24px;
          
          .username {
            font-size: 18px;
            font-weight: 600;
            margin-bottom: 8px;
          }
          
          .user-dept, .user-role, .join-time {
            margin: 4px 0;
            color: rgba(0, 0, 0, 0.65);
          }
        }
        
        .user-stats {
          padding-top: 16px;
          border-top: 1px solid #f0f0f0;
          
          .stat-item {
            text-align: center;
            
            .stat-value {
              font-size: 16px;
              font-weight: 600;
              margin-bottom: 4px;
            }
            
            .stat-label {
              font-size: 12px;
              color: rgba(0, 0, 0, 0.45);
            }
          }
        }
      }
    }
    
    .right-panel {
      flex: 1;
      min-width: 0;
    }
  }
  
  .avatar-wrapper {
    display: flex;
    align-items: center;
  }
  
  .signature-container {
    margin-top: 16px;
    
    .signature-pad-container {
      display: flex;
      flex-direction: column;
      gap: 16px;
      margin: 16px 0;
      
      .signature-pad-wrapper {
        border: 1px dashed gray;
        height: 200px;
        width: 600px;
        .signature-pad {
          width: 100%;
          height: 100%;
        }
      }
      
      .signature-controls {
        width: 100%;
      }
    }
    
    .color-picker {
      display: flex;
      flex-wrap: wrap;
      width: 150px;
      
      .color-item {
        width: 24px;
        height: 24px;
        margin: 2px;
        border-radius: 4px;
        cursor: pointer;
        border: 1px solid #d9d9d9;
        
        &:hover {
          transform: scale(1.1);
        }
      }
    }
    
    .color-preview {
      display: inline-block;
      width: 16px;
      height: 16px;
      border-radius: 2px;
      margin-right: 8px;
      vertical-align: middle;
    }
    
    .signature-preview {
      margin-top: 24px;
      
      .current-signature {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 16px;
        
        .signature-image {
          max-width: 300px;
          max-height: 150px;
          border: 1px solid #f0f0f0;
          border-radius: 4px;
          padding: 8px;
        }
        
        .signature-actions {
          margin-top: 8px;
        }
      }
    }
  }
  

  
  /* 地图弹窗相关样式 */
  .map-modal-content {
    .selected-address-info {
      h4 {
        margin-bottom: 8px;
        color: rgba(0, 0, 0, 0.85);
      }
      
      p {
        margin-bottom: 4px;
        
        strong {
          color: rgba(0, 0, 0, 0.85);
        }
      }
    }
  }
}
</style>
